package com.koron.order.patrol.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.bean.query.PageQuery;
import com.koron.bean.scheduleShift.ScheduleShift;
import com.koron.bean.scheduleShift.ShiftStaff;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.staff.Constant;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.OrgCacheUtils;
import com.koron.order.common.tools.CommonCodeTools;
import com.koron.order.common.tools.OrderCodeEnum;
import com.koron.order.patrol.bean.po.PatrolPo;
import com.koron.order.patrol.bean.po.PatrolUserPo;
import com.koron.order.patrol.bean.query.PatrolQuery;
import com.koron.order.patrol.mapper.PatrolMapper;
import com.koron.order.patrol.service.PatrolService;
import com.koron.order.patrol.service.PatrolUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 巡视工单-基础信息(Patrol)表服务实现类
 *
 * @author zhouj
 * @since 2021-10-26 15:32:38
 */
@Slf4j
@Service("patrolService")
public class PatrolServiceImpl implements PatrolService {

    @Autowired
    PatrolUserService patrolUserService;
    @Autowired
    OrgCacheUtils orgCacheUtils;

    @Override
    @TaskAnnotation("insertOrUpdate")
    public int insertOrUpdate(SessionFactory factory, PatrolPo patrolPo) {

        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);

        if (StringUtils.isEmpty(patrolPo.getId())) {
            patrolPo.setId(CodeTools.getCode32());
        }

        if (StringUtils.isEmpty(patrolPo.getCode())) {
            OrgBean orgBean = orgCacheUtils.getOrgById(patrolPo.getBelongDeptId());
            if(orgBean!=null){
                String simpleEn = orgBean.getPrefix();
                patrolPo.setCode(CommonCodeTools.getOrderCode(OrderCodeEnum.XS,simpleEn));
            }else {
                patrolPo.setCode(CommonCodeTools.getNormalOrderCode(OrderCodeEnum.XS));
            }
        }

        return mapper.insertOrUpdate(patrolPo);
    }

    @Override
    @TaskAnnotation("insertOrUpdateBatch")
    public int insertOrUpdateBatch(SessionFactory factory, List<PatrolPo> patrolList) {

        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);

        return mapper.insertOrUpdateBatch(patrolList);
    }

    @Override
    @TaskAnnotation("insert")
    public int insert(SessionFactory factory, PatrolPo patrol) {

        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);

        return mapper.insert(patrol);
    }

    @Override
    @TaskAnnotation("insertBatch")
    public int insertBatch(SessionFactory factory, List<PatrolPo> patrolList) {

        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);

        return mapper.insertBatch(patrolList);
    }

    @Override
    @TaskAnnotation("update")
    public int update(SessionFactory factory, PatrolPo patrol) {
        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);
        return mapper.update(patrol);
    }

    @Override
    @TaskAnnotation("updatePatrolStaff")
    public int updatePatrolStaff(SessionFactory factory, ScheduleShift scheduleShift) {

        List<ShiftStaff> staffs = scheduleShift.getStaffs();

        Assert.notEmpty(staffs, "人员列表不能为空");

        //转换计划及交接班 字典
        String key = getKey(scheduleShift.getStaffType());

        scheduleShift.setStaffType(key);

        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);

        // 查询所有符合条件的巡视工单
        List<PatrolPo> patrolList = mapper.queryPatrolByCondition(scheduleShift);

        if (!CollectionUtils.isEmpty(patrolList)) {
            log.info("查询到{}条需要指定人员的巡视工单", patrolList.size());
            List<PatrolUserPo> patrolUserPos = new ArrayList<>();
            for (PatrolPo patrol : patrolList) {
                String patrolId = patrol.getId();
                //根据 patrolId 更新巡视人员
                for (int i = 0; i < staffs.size(); i++) {
                    PatrolUserPo patrolUserPo = new PatrolUserPo();
                    patrolUserPo.setWorker(staffs.get(i).getStaffBy());
                    patrolUserPo.setWorkerName(staffs.get(i).getStaffName());
                    patrolUserPo.setSort(i);
                    patrolUserPo.setPatrolId(patrolId);
                    patrolUserPo.setPatrolDeptId(scheduleShift.getDeptId());
                    patrolUserPo.setPatrolDeptName(scheduleShift.getDeptName());
                    patrolUserPos.add(patrolUserPo);
                }
            }
            return patrolUserService.insertOrUpdateBatch(factory, patrolUserPos);
        }
        log.info("未找到需要指定人员的巡视工单");
        return 0;
    }

    public String getKey(String staffType) {
        Map<String, String> map = Constant.StaffingWay.map;

        Set<String> keys = map.keySet();

        for (String key : keys) {
            String value = map.get(key);
            if (value.equals(staffType)) {
                return key;
            }
        }
        return null;
    }

    @Override
    @TaskAnnotation("deleteById")
    public int deleteById(SessionFactory factory, String id) {

        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);
        return mapper.deleteById(id);
    }

    @Override
    @TaskAnnotation("queryById")
    public PatrolPo queryById(SessionFactory factory, String id) {

        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);

        return mapper.queryById(id);
    }

    @Override
    @TaskAnnotation("queryList")
    public List<PatrolPo> queryList(SessionFactory factory, PatrolQuery query) {

        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);

        List<PatrolPo> list = mapper.queryList(query);

        return list;
    }

    @Override
    @TaskAnnotation("queryPageList")
    public PageInfo queryPageList(SessionFactory factory, PatrolQuery query, PageQuery pageQuery) {

        PageHelper.startPage(pageQuery.getPage(), pageQuery.getPageSize(), pageQuery.getOrderBy());
        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);

        List<PatrolPo> list = mapper.queryList(query);

        return new PageInfo<PatrolPo>(list);
    }
    @Override
    public int updatePatrolInsertFlag(SessionFactory factory, PatrolPo patrolPo) {

        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);

        return mapper.updatePatrolInsertFlag(patrolPo);
    }

    @TaskAnnotation("staPatrolInfo")
    @Override
    public List<Map<String, Object>> staPatrolInfo(SessionFactory factory, String patrolDeptId, String startTime, String endTime) {
        PatrolMapper mapper = factory.getMapper(PatrolMapper.class);
        List<PatrolPo> patrolPoList = mapper.staPatrolInfo(patrolDeptId, startTime, endTime);

        Map<String, List<PatrolPo>> groupedPatrolMap = patrolPoList.stream()
                .collect(Collectors.groupingBy(patrolPo -> DateUtil.format(patrolPo.getPlanStartTime(), DatePattern.NORM_DATE_PATTERN)));

        List<Map<String, Object>> tempList = new ArrayList<>(groupedPatrolMap.size());
        for (Map.Entry<String, List<PatrolPo>> entry : groupedPatrolMap.entrySet()) {
            Map<String, Object> temp = new HashMap<>();
            temp.put("date", entry.getKey());
            temp.put("poList", entry.getValue());
            tempList.add(temp);
        }

        // 按照日期时间升序
        tempList.sort((o1,o2)->{
            String date1 = (String) o1.get("date");
            String date2 = (String) o2.get("date");
            return date1.compareTo(date2);
        });

        return tempList;
    }

}